<template>
  <Container class="manage-list">
    <Tabs>
      <Button
        size="large"
        class="item"
        type="primary"
        slot="extra"
        icon="md-add"
        @click="onAdd">添加服务商品</Button>
      <TabPane label="服务项目">
        <Table
          :height="options.tableHeight"
          stripe
          :columns="list.columns"
          :data="list.data"
          no-data-text="亲，没有找到相关记录哦！~"></Table>
        <Loader :status="list.status" @refresh="getData"></Loader>
      </TabPane>
    </Tabs>
  </Container>
</template>
<script>
import { formatCurrency } from '@/util'
import table from '@/table'
import ProjectListData from './list/ProjectListData'
export default {
  data() {
    return {
      options: {
        tableHeight: 300
      },
      list: ProjectListData
    }
  },
  mounted() {
    this.initTable()
    this.$bus.$on('onEdit', ({ id, categoryId }) => this.onEdit(id, categoryId))
    this.$bus.$on('onDelete', ({ id, index }) => this.onDelete(id, index))
    this.$bus.$on('onSwitch', this.onSwitch)
    this.getData()
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    ...table,
    getData() {
      this.list.status = 'loading'
      this.$ajaxGet('/server/store_server/list_server_all').then(data => {
        this.list.data = (data || []).map(item => {
          return {
            id: item.id,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            name: item.name,
            price: formatCurrency(item.price, true),
            isEnabled: item.isEnabled
          }
        })
        this.list.status = 'pass'
        this.backTableTop()
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    onEdit(id, categoryId) {
      this.$router.push({
        name: 'product/project/edit',
        query: {
          id,
          categoryId
        }
      })
    },
    onSwitch(id, val, index) {
      let url = val ? '/server/store_server/enable/' : '/server/store_server/disable/'
      let text = val ? '启用' : '关闭'
      this.$set(this.list.data[index], 'isEnabled', val)
      this.$ajaxPost(url + id).then(data => {
        this.$Notice.success({
          title: text + '成功'
        })
      }).catch(() => {
        setTimeout(() => {
          this.$set(this.list.data[index], !val)
        }, 200)
      })
    },
    onDelete(id, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '删除服务项目后，关联的溢价规则将一并册除！',
        loading: true,
        onOk: () => {
          this.$jsonPost('/server/store_server/deleted/' + id).then(data => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.list.data.splice(index, 1)
            this.$Modal.remove()
          }).catch(() => {
            this.$Modal.remove()
          })
        }
      })
    },
    onAdd() {
      this.$router.push({
        name: 'product/project/edit'
      })
    }
  }
}
</script>
